package org.freedoit.shared.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

import org.freedoit.shared.exception.ServerException;

public class Utils {

	private static final Logger log = Logger.getLogger(Utils.class.getName());
    private static char hexDigits[] = {       //
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',  'E', 'F'}; 
	private static String hexString(byte[] source) {
	    char str[] = new char[16 * 2];
	    //
	    int k = 0;                                //
	    for (int i = 0; i < 16; i++) {          //
	        byte byte0 = source[i];                 // 
	        str[k++] = hexDigits[byte0 >>> 4 & 0xf];  // 
	        //  
	        str[k++] = hexDigits[byte0 & 0xf];            // 
	    }  
	    return new String(str);  
	}
	public static String getMD5(String plainText) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			log.severe(e.getMessage());
			throw new ServerException(e);
		}
	    try {
	        md5.update(plainText.getBytes("UTF-8"));
	    } catch (UnsupportedEncodingException e) {
			log.severe(e.getMessage());
			throw new ServerException(e);
	    }
		byte[] resultBytes= md5.digest();
		return hexString(resultBytes);
	}
}
